//
//  NSPhotoViewController.m
//  Meboo
//
//  Created by kyo on 2024/4/18.
//

#import "NSPhotoViewController.h"
#import "NSPhotoNavView.h"
#import "NSPhotoCameraCell.h"
#import "NSPhotoImageCell.h"
#import <Photos/Photos.h>
#import <AVFoundation/AVFoundation.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import "GXPHKitTool.h"
#import "GXPhotoAssetModel.h"
#import "NSPrivatePhotoModel.h"
#import "GKPhotoBrowser.h"
#import "NSGKPhotoBrowser.h"
#import "NSChatPrivateGuideView.h"
#import "NSPrivateNullView.h"
@interface NSPhotoViewController ()
<
UICollectionViewDelegate,
UICollectionViewDataSource,
UIImagePickerControllerDelegate,
GKPhotoBrowserDelegate
>
//背景图
@property (nonatomic, strong) UIImageView *backImageView;
//图片数组
@property (nonatomic, strong) NSMutableArray *imageArr;
//普通相册
@property (nonatomic , strong) UICollectionView *photoCollectionView;
//私密相册
@property (nonatomic , strong) UICollectionView *privateCollectionView;
//头部组件
@property (nonatomic , strong) NSPhotoNavView *photoNavView;
//相册asset数组
@property (nonatomic , strong) NSMutableArray *dataArr;
//引导视图
@property (nonatomic , strong) NSChatPrivateGuideView *privateGuideView;
//空数据
@property (nonatomic , strong) NSPrivateNullView *privateNullView;
//防截屏
@property (nonatomic, strong) UIView *secView;
@end

@implementation NSPhotoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = HEXS(@"ffffff");
    [self setupUI];
    [self getAllPhotos];
    [self getPrivateData];
    
    [MBNotificationCenter addObserver:self selector:@selector(getPrivateData) name:REFRESH_PRIVATE_LIST object:nil];
}


#pragma mark - Private Method
//获取隐私图片
- (void)getPrivateData {
    __WeakSelf
    [[MBChatDataManager sharedManager] getPrivatePhoteList:^(BOOL success) {
        if (success && [MBChatDataManager sharedManager].privateDataArr) {
            [weakSelf.privateCollectionView reloadData];
        }
    }];
}

//获取本地图片
- (void)getAllPhotos {
    __WeakSelf
    [self.imageArr removeAllObjects];
    [[GXPHKitTool sharedPHKitTool] getCameraRollAssetsWithResultBlock:^(PHAuthorizationStatus status,NSArray<GXPhotoAssetModel *> *imageArray) {
        //倒序
        [imageArray enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            [self.imageArr addObject:obj];
        }];
        
        [weakSelf.photoCollectionView reloadData];
    }];
    
}


#pragma mark - Action
- (void)cameraAction {
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];//读取设备授权状态
    if(authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied){
//            [SVProgressHUD showInfoWithStatus:RVString(@"CameraPermissions")];
    }else{
        //打开照相机
        if ([UIImagePickerController  isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            UIImagePickerController  *picker = [[UIImagePickerController alloc]init];
            picker.mediaTypes = [[NSArray alloc] initWithObjects:(NSString *)kUTTypeImage, (NSString *)kUTTypeMovie, nil];
            picker.sourceType = UIImagePickerControllerSourceTypeCamera;
            picker.allowsEditing = NO;
            picker.delegate = self;
            [self.currentViewController presentViewController:picker animated:YES completion:^{}];
        }
    }
}

//image是要保存的图片
- (void)saveImage:(UIImage *)image {
    UIImageWriteToSavedPhotosAlbum(image, self, @selector(savedPhotoImage:didFinishSavingWithError:contextInfo:), nil);
}
//保存完成后调用的方法
- (void)savedPhotoImage:(UIImage*)image didFinishSavingWithError: (NSError *)error contextInfo: (void *)contextInfo {
   if (error) {
       NSLog(@"保存图片出错%@", error.localizedDescription);
   }
   else {
       NSLog(@"保存图片成功");
       [self getAllPhotos];
   }
}

//videoPath为视频下载到本地之后的本地路径
- (void)saveVideo:(NSString *)videoPath{

    if (videoPath) {

            if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(videoPath)) {
                //保存相册核心代码
                UISaveVideoAtPathToSavedPhotosAlbum(videoPath, self, @selector(video:didFinishSavingWithError:contextInfo:), nil);
            }
        
    }

}
//保存视频完成之后的回调
- (void)video:(NSString *)videoPath didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    if (error) {
        NSLog(@"保存视频失败%@", error.localizedDescription);
    }
    else {
        NSLog(@"保存视频成功");
        [self getAllPhotos];
    }
  
}

#pragma mark - UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    [picker dismissViewControllerAnimated:NO completion:nil];
    __WeakSelf
    UIImage *editedImage = info[UIImagePickerControllerOriginalImage];
    if (editedImage) {
        [self.dataArr removeAllObjects];
        GKPhoto *data = [GKPhoto new];
        data.image = editedImage;
        [self.dataArr addObject:data];
        __weak NSGKPhotoBrowser *browser = [NSGKPhotoBrowser photoBrowserWithPhotos:self.dataArr currentIndex:0];
        browser.showStyle = GKPhotoBrowserShowStyleZoom;
        browser.hideStyle = GKPhotoBrowserHideStyleZoomScale;
        browser.animDuration = 0.1;
        browser.isScreenRotateDisabled = YES;
        browser.delegate = self;
        browser.sendBlock = ^(BOOL isPrivate) {
            [weakSelf sendAction:browser.curPhotoView.imageView.image isPrivate:isPrivate videoUrl:nil duration:0 videoPath:@""];
        };
        [browser showFromVC:self];
        //图片
        [self saveImage:editedImage];
    } else {
        //视频
        NSURL*url = info[UIImagePickerControllerMediaURL];
        GKPhoto *data = [GKPhoto new];
        data.videoUrl = url;
        [self.dataArr addObject:data];
        __weak NSGKPhotoBrowser *browser = [NSGKPhotoBrowser photoBrowserWithPhotos:self.dataArr currentIndex:0];
        browser.showStyle = GKPhotoBrowserShowStyleZoom;
        browser.hideStyle = GKPhotoBrowserHideStyleZoomScale;
        browser.animDuration = 0.1;
        browser.isScreenRotateDisabled = YES;
        browser.delegate = self;
        browser.sendBlock = ^(BOOL isPrivate) {
            [weakSelf sendAction:browser.curPhotoView.imageView.image isPrivate:isPrivate videoUrl:url duration:0 videoPath:@""];
        };
        [browser showFromVC:self];
        [self saveVideo:url.path];
    }
    
}

#pragma mark -- collectionView  delegate datasource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (collectionView == self.photoCollectionView) {
        return self.imageArr.count + 1;
    } else {
        return [MBChatDataManager sharedManager].privateDataArr.count;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (collectionView == self.photoCollectionView) {
        if (indexPath.row == 0) {
            NSPhotoCameraCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"NSPhotoCameraCell" forIndexPath:indexPath];
            return cell;
        } else {
            NSPhotoImageCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"NSPhotoImageCell" forIndexPath:indexPath];
            GXPhotoAssetModel *model = self.imageArr[indexPath.row-1];
            cell.assetModel= model;
            return cell;
        }
    } else {
        NSPhotoImageCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"PrivateNSPhotoImageCell" forIndexPath:indexPath];
        NSPrivatePhotoModel *model = [MBChatDataManager sharedManager].privateDataArr[indexPath.row];
        cell.privateModel= model;
        return cell;
    }

}

//设置每个section的UIEdgeInsets
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(MBHeightScale(10), MBWidthScale(3), MBHeightScale(10), MBWidthScale(3));
}

//设置列间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return MBWidthScale(3);
}

//设置每个item水平间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return MBWidthScale(3);
}

//定义每一个cell的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake((ScreenWidth-MBWidthScale(13))/3, (ScreenWidth-MBWidthScale(13))/3);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    NSString *ioStr = @"";
    NSPhotoImageCell * cell = (NSPhotoImageCell *)[self collectionView:collectionView cellForItemAtIndexPath:indexPath];
    __WeakSelf
    if (collectionView == self.photoCollectionView) {
        if (indexPath.row == 0) {
            [self cameraAction];
        } else {
            GXPhotoAssetModel *model = self.imageArr[indexPath.row-1];
//            self.photoPreView.assetModel = model;
//            self.photoPreView.isPrivate = NO;
//            [UIView animateWithDuration:0.2 animations:^{
//                weakSelf.photoPreView.alpha = 1;
//            }];
            
            [self.dataArr removeAllObjects];
            GKPhoto *data = [GKPhoto new];
//            data.imageAsset = model.asset;
//            data.videoUrl = [NSURL URLWithString:@"https://storage.googleapis.com/meboo-online-b68e7.appspot.com/test/5ba097b216098.mp4"];
            if (model.asset.mediaType != PHAssetMediaTypeVideo) {
                data.imageAsset = model.asset;
            } else {
                data.videoAsset = model.asset;
            }
            [self.dataArr addObject:data];
            __weak NSGKPhotoBrowser *browser = [NSGKPhotoBrowser photoBrowserWithPhotos:self.dataArr currentIndex:0];
            if (model.asset.mediaType == PHAssetMediaTypeVideo) {
                browser.isVideo = YES;
            }
            browser.showStyle = GKPhotoBrowserShowStyleZoom;
            browser.hideStyle = GKPhotoBrowserHideStyleZoomScale;
            browser.animDuration = 0.1;
            browser.isScreenRotateDisabled = YES;
            browser.videoLength = model.asset.duration;
            browser.delegate = self;
            browser.sendBlock = ^(BOOL isPrivate) {
                [weakSelf sendAction:model.asset.mediaType == PHAssetMediaTypeVideo ? nil : browser.curPhotoView.imageView.image isPrivate:isPrivate videoUrl:cell.videoUrl duration:model.asset.duration videoPath:@""];
            };
            [browser showFromVC:self];
        }
        ioStr = @"Chat_Album_P/V";
    } else {
        NSPrivatePhotoModel *model = [MBChatDataManager sharedManager].privateDataArr[indexPath.row];
        [self.dataArr removeAllObjects];
        GKPhoto *data = [GKPhoto new];
        if (model.videoLength.length == 0) {
            data.url = [NSURL URLWithString:model.imageUrl];
        } else {
            data.videoUrl = [NSURL URLWithString:model.imageUrl];
        }
        [self.dataArr addObject:data];
        NSGKPhotoBrowser *browser = [NSGKPhotoBrowser photoBrowserWithPhotos:self.dataArr currentIndex:0];
        browser.showStyle = GKPhotoBrowserShowStyleZoom;
        browser.hideStyle = GKPhotoBrowserHideStyleZoomScale;
        browser.animDuration = 0.1;
        browser.isScreenRotateDisabled = YES;
        browser.videoLength = 999999999;
        browser.sendBlock = ^(BOOL isPrivate) {
            [weakSelf sendAction:cell.timeLabel.hidden ? cell.photoImageView.image : nil isPrivate:YES videoUrl:cell.videoUrl duration:[model.videoLength integerValue] videoPath:cell.videoPath];
        };
        [browser showFromVC:self];
        ioStr = @"Chat_PrivateAlbum_P/V";
    }
    /**
     埋点
     点击本地相册任意照片/视频Chat_Album_P/V
     点击私密相册任意照片/视频Chat_PrivateAlbum_P/V
     */
    [[NSIOApiManager sharedManager] setIOWithEventName:ioStr];
}

#pragma mark -- GKPhotoBrowserDelegate
- (void)photoBrowser:(GKPhotoBrowser *)browser singleTapWithIndex:(NSInteger)index {
    for (UIView *view in browser.view.subviews) {
        if (view.tag > 1000) {
            view.hidden = YES;
        }
    }
}

- (void)sendAction:(UIImage * _Nullable)image isPrivate:(BOOL)isPrivate videoUrl:(NSURL *)videoUrl duration:(NSInteger)duration videoPath:(NSString *)videoPath {
    [self.navigationController popViewControllerAnimated:YES];
    [MBProgressHUD hideHUD];
    RCMessage *message;
    if (image) {
        RCImageMessage *mediaMessageContent = [RCImageMessage messageWithImage:image];
        mediaMessageContent.full = YES; // 图片消息支持设置以原图发送
        message = [[RCMessage alloc] initWithType:ConversationType_PRIVATE
                                                    targetId:self.targetId
                                                   direction:MessageDirection_SEND
                                                     content:mediaMessageContent];
    } else {
        UIImage *firstImage = [self getThumbnailImage:videoUrl];
        RCSightMessage *mediaMessageContent;
        // 将视频保存到沙盒目录下
        NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
        NSString *Path = [documentsPath stringByAppendingPathComponent:@"video.mp4"];
        
        if (videoPath.length > 0) {
            Path = videoPath;
        } else {
            NSData *videoData = [NSData dataWithContentsOfURL:videoUrl];
            [videoData writeToFile:Path atomically:YES];
        }
        
        
        mediaMessageContent = [RCSightMessage messageWithLocalPath:Path thumbnail:firstImage duration:duration];
        message = [[RCMessage alloc] initWithType:ConversationType_PRIVATE
                                                    targetId:self.targetId
                                                   direction:MessageDirection_SEND
                                                     content:mediaMessageContent];
    }
    
    
    

    message.canIncludeExpansion = YES;
//    message.expansionDic = @{@"isPrivate":isPrivate ? @"1" : @"0"};
    message.expansionDic = @{@"isPrivate":isPrivate ? @"true" : @"0"};
    [[RCIM sharedRCIM] sendMediaMessage:message
                            pushContent:nil
                               pushData:nil
                               progress:^(int progress, RCMessage *progressMessage) {
        //媒体上传进度
    }
                           successBlock:^(RCMessage *successMessage) {
        //成功
        NSLog(@"");
        //        if (weakSelf.sendImageBlock) {
        //            weakSelf.sendImageBlock();
        //        }
    }
                             errorBlock:^(RCErrorCode nErrorCode, RCMessage *errorMessage) {
        //失败
        NSLog(@"");
    }
                                 cancel:^(RCMessage *cancelMessage) {
        //取消
        NSLog(@"");
    }];
}

//获取视频的缩略图(第一帧)
- (UIImage *)getThumbnailImage:(NSURL *)videoUrl {
    UIImage *theImage = nil;
     AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoUrl options:nil];
     AVAssetImageGenerator *generator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
     generator.appliesPreferredTrackTransform = YES;
     NSError *err = NULL;
     CMTime time = CMTimeMake(1, 60);
     CGImageRef imgRef = [generator copyCGImageAtTime:time actualTime:NULL error:&err];

     theImage = [[UIImage alloc] initWithCGImage:imgRef];
     CGImageRelease(imgRef);
     return theImage;
}

- (UIView *)getBgView{
    UITextField *bgTextField = [[UITextField alloc] init];
    [bgTextField setSecureTextEntry:true];
    
    UIView *bgView = bgTextField.subviews.firstObject;
    [bgView setUserInteractionEnabled:true];
    bgView.backgroundColor = UIColor.clearColor;
    return bgView;
}


#pragma mark - UI
- (void)setupUI {
    
    [self.view addSubview:self.secView];
    [self.secView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    [self.secView addSubview:self.backImageView];
    [self.backImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    [self.secView addSubview:self.photoNavView];
    [self.photoNavView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(StatusBarAndNavigationBarHeight);
        make.right.left.top.equalTo(self.view);
    }];
    
    [self.secView addSubview:self.privateCollectionView];
    [self.privateCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.photoNavView.mas_bottom).offset(MBHeightScale(20));
        make.right.left.bottom.equalTo(self.view);
    }];
    
    [self.secView addSubview:self.photoCollectionView];
    [self.photoCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.photoNavView.mas_bottom).offset(MBHeightScale(20));
        make.right.left.bottom.equalTo(self.view);
    }];
    
    [self.privateCollectionView addSubview:self.privateNullView];
    [self.privateNullView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.photoNavView.mas_bottom).offset(MBHeightScale(20));
        make.right.left.bottom.equalTo(self.view);
    }];
    
    [self.privateCollectionView addSubview:self.privateGuideView];
    [self.privateGuideView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.photoNavView.mas_bottom).offset(MBHeightScale(20));
        make.right.left.bottom.equalTo(self.view);
    }];
}

#pragma mark - Setter && Getter

- (NSMutableArray *)imageArr {
    if (!_imageArr) {
        _imageArr = [NSMutableArray array];
    }
    return _imageArr;
}

- (UICollectionView *)photoCollectionView {
    if (!_photoCollectionView) {
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        flowLayout.minimumInteritemSpacing = 0;
        flowLayout.minimumLineSpacing = 0;
        _photoCollectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:flowLayout];
        _photoCollectionView.backgroundColor = UIColor.clearColor;
        _photoCollectionView.delegate = self;
        _photoCollectionView.dataSource = self;
        _photoCollectionView.showsVerticalScrollIndicator = NO;
        _photoCollectionView.showsHorizontalScrollIndicator = NO;
        [_photoCollectionView registerClass:[NSPhotoCameraCell class] forCellWithReuseIdentifier:@"NSPhotoCameraCell"];
        [_photoCollectionView registerClass:[NSPhotoImageCell class] forCellWithReuseIdentifier:@"NSPhotoImageCell"];
    }
    return _photoCollectionView;
}

- (UICollectionView *)privateCollectionView {
    if (!_privateCollectionView) {
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        flowLayout.minimumInteritemSpacing = 0;
        flowLayout.minimumLineSpacing = 0;
        _privateCollectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:flowLayout];
        _privateCollectionView.backgroundColor = UIColor.clearColor;
        _privateCollectionView.delegate = self;
        _privateCollectionView.dataSource = self;
        _privateCollectionView.hidden = YES;
        _privateCollectionView.showsVerticalScrollIndicator = NO;
        _privateCollectionView.showsHorizontalScrollIndicator = NO;
        [_privateCollectionView registerClass:[NSPhotoImageCell class] forCellWithReuseIdentifier:@"PrivateNSPhotoImageCell"];
    }
    return _privateCollectionView;
}

- (UIImageView *)backImageView {
    if (!_backImageView) {
        _backImageView = [UIImageView new];
        _backImageView.image = ImageWithName(@"home_back_image");
    }
    return _backImageView;
}

- (NSPhotoNavView *)photoNavView {
    if (!_photoNavView) {
        __WeakSelf
        _photoNavView = [NSPhotoNavView new];
        _photoNavView.photoBlock = ^(BOOL isPrivate) {
            if (isPrivate) {
                weakSelf.privateCollectionView.hidden = NO;
                weakSelf.photoCollectionView.hidden = YES;
                if ([MBUserAccount defaultAccount].isVip) {
                    //会员 判断有无数据
                    if ([MBChatDataManager sharedManager].privateDataArr.count == 0) {
                        //没数据
                        weakSelf.privateGuideView.hidden = NO;
                    } else {
                        //有数据
                    }
                } else {
                    //非会员
                    weakSelf.privateGuideView.hidden = NO;
                }
            } else {
                weakSelf.privateCollectionView.hidden = YES;
                weakSelf.photoCollectionView.hidden = NO;
            }
        };
    }
    return _photoNavView;
}

- (NSMutableArray *)dataArr {
    if (!_dataArr) {
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}

- (NSChatPrivateGuideView *)privateGuideView {
    if (!_privateGuideView) {
        __WeakSelf
        _privateGuideView = [NSChatPrivateGuideView new];
        _privateGuideView.hidden = YES;
        _privateGuideView.nullBlock = ^{
            weakSelf.privateGuideView.hidden = YES;
            weakSelf.privateNullView.hidden = NO;
        };
    }
    return _privateGuideView;
}

- (NSPrivateNullView *)privateNullView {
    if (!_privateNullView) {
        __WeakSelf
        _privateNullView = [NSPrivateNullView new];
        _privateNullView.hidden = YES;
        _privateNullView.addBlock = ^{
            [weakSelf.photoNavView photoAction];
        };
    }
    return _privateNullView;
}

- (UIView *)secView {
    if (!_secView) {
        _secView = [self getBgView];
    }
    return _secView;
}
@end
